/**
 * 点击注册 
 *      获取输入框的内容存入localStorage
 *      如果localStorage该用户已存在，提示该用户已存在
 */
function registerUser() {
    let stoUsers = localStorage.getItem('xiongmaoUsers')
    stoUsers = JSON.parse(stoUsers) || []
    let username = $('input[name="username"]').val()
    let pwd = $('input[name="pwd"]').val()
    checkEmpty()
    if (stoUsers.find(item => item.username == username)) {
        alert('该用户已存在！')
    } else {
        let reg = /[a-zA-Z]{1,}[0-9]{7,}/
        if (!username || !pwd || !reg.test(pwd)) {
            alert('信息有误！')
        } else {
            let user = {
                username,
                password: pwd,
                state: false
            }
            stoUsers.push(user)
            localStorage.setItem('xiongmaoUsers', JSON.stringify(stoUsers))
            alert('恭喜注册成功!')
        }

    }
}

/**
 * 点击登录
 *      获取输入框的值 与 localStorage的值对比，若存在跳转至主页面
 *      否则提示用户名或密码错误
 */
function toIndexPage() {
    let stoUsers = localStorage.getItem('xiongmaoUsers')
    stoUsers = JSON.parse(stoUsers) || []
    let username = $('input[name="username"]').val()
    let pwd = $('input[name="pwd"]').val()
    if (!username || !pwd) {
        alert('用户名和密码都不能为空！')
    } else {
        let user = stoUsers.find(item => item.username == username && item.password == pwd)

        if (user) {
            alert('登陆成功')
            user.state = true
            console.log(user);
            location.href = 'index.html'
            localStorage.setItem('xiongmaoUsers', JSON.stringify(stoUsers))
        } else {
            alert('用户名或密码错误!')
        }
    }

}

/**
 * 用户名非空 和 密码非空 难度验证
 */
function checkEmpty() {
    $('form').on('blur', 'input[name="username"]', function () {
        // console.log($(this).val());
        if (!$(this).val()) {
            $(this).next().next().html('*用户名不能为空')
            $(this).next().next()[0].style.color = 'red'
        }
    })

    $('form').on('blur', 'input[name="pwd"]', function () {
        // console.log($(this).val());
        let reg = /[a-zA-Z]{1,}[0-9]{7,}/

        if (!$(this).val()) {
            $(this).next().next().html('*密码不能为空')
            $(this).next().next()[0].style.color = 'red'
        } else if (!reg.test($(this).val())) {
            $(this).next().next().html('*英文字母开头，英文字母数字和组合,至少8位')
            $(this).next().next()[0].style.color = 'red'
        } else {
            $(this).next().next().html('')
        }
        console.log(reg.test($(this).val()))
    })
}

checkEmpty()